package com.fzy.common.spring;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 字符串转日期的转换器
 *
 * @author 冯赵杨
 * @create 2018/8/3
 */
public class StringToDateConverter implements Converter<String, Date> {

    /**
     * 日期格式化表达式
     */
    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";


    /**
     * 时间格式化表达式
     */
    private static final String shortDateFormat = "yyyy-MM-dd";
    /**
     * 日期格式关键字
     */
    private static final String DATE_KEY = "-";
    /**
     * 时间格式关键字
     */
    private static final String DATETIME_KEY = ":";
    /**
     * 日期Long型 通配符
     */
    private static final String DATE_LONG_KEY = "^\\d+$";

    /**
     * @see Converter#convert(Object)
     */
    @Override
    public Date convert(String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        source = source.trim();
        try {
            if (source.contains(DATE_KEY)) {
                SimpleDateFormat formatter;
                if (source.contains(DATETIME_KEY)) {
                    formatter = new SimpleDateFormat(dateFormat);
                } else {
                    formatter = new SimpleDateFormat(shortDateFormat);
                }
                return formatter.parse(source);
            } else if (source.matches(DATE_LONG_KEY)) {
                Long lDate = new Long(source);
                return new Date(lDate);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", source));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", source));
    }

}